package com.itheima.reggie.service.impl;

import com.itheima.reggie.dao.*;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.utils.UUIDUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired(required = false)
    private OrderDao orderDao;
    @Autowired(required = false)
    private ShoppingCartDao shoppingCartDao;
    @Autowired(required = false)
    private UserDao userDao;
    @Autowired(required = false)
    private OrderDetailDao orderDetailDao;
    @Autowired(required = false)
    private AddressBookDao addressBookDao;
    @Override
    @Transactional
    public void sumbit(Orders orders) {
//        获得订单id
        Long userId = orders.getUserId();
//        生成一个订单Id
        Long uuidInOrderId = UUIDUtils.getUUIDInOrderId().longValue();
//        查找用户信息
       User user= userDao.findById(userId);
//       获取地址信息
        AddressBook addressBook = addressBookDao.findById(orders.getAddressBookId());
//        查找购物车信息
        List<ShoppingCart> cart = shoppingCartDao.findCart(userId);
        List<OrderDetail>orderDetailList=new ArrayList<>();
        BigDecimal totalAmount=new BigDecimal(0+"");
        for (ShoppingCart shoppingCart : cart) {
//        将购物项信息放入订单项信息
            OrderDetail orderDetail=new OrderDetail();
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setOrderId(uuidInOrderId);
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setAmount(shoppingCart.getAmount());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetailList.add(orderDetail);
            orderDetailDao.save(orderDetailList);
            totalAmount=totalAmount.add(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber()+"")));
        }
//         插入订单
        orders.setId(uuidInOrderId);
        orders.setNumber(uuidInOrderId+"");
        orders.setStatus(1);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
//        orders.setPayMethod();
        orders.setAmount(totalAmount);
//        orders.setRemark();
        orders.setUserName(user.getName());
        orders.setPhone(user.getPhone());//订单所属的用户的用户名
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orderDao.save(orders);

    }
}
